<template>
  <div>
    <el-form :inline="true" :model="queryForm" class="demo-form-inline">
      <el-form-item label="用户名">
        <el-input v-model="queryForm.userName" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="queryForm.phoneNumber" placeholder="手机号"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryForm.status" placeholder="状态" clearable>
          <el-option label="正常" value="0"></el-option>
          <el-option label="停用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门">
        <el-select v-model="queryForm.deptId" placeholder="部门" clearable>
          <el-option :key="d.id" v-for="d in deptList" :label="d.deptName" :value="d.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
            v-model="createTimeArray"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onQuery">查询</el-button>
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="danger" @click="batchDel">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          prop="id"
          label="编号"
          width="55">
      </el-table-column>
      <el-table-column
          prop="userName"
          label="姓名"
          width="100">
      </el-table-column>
      <el-table-column
          prop="phonenumber"
          label="手机号"
          width="100">
      </el-table-column>
      <el-table-column
          prop="avatar"
          label="头像"
          width="150">
        <!--        slot-scope=“scope” 的scope代表一行记录。
        如果想知道该记录是第几行，则它的索引是scope.$index，
        如果想知道该行记录的所有值，则从scope.row来获取-->
        <template v-slot:default="scope">
          <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.avatar"
          ></el-image>
        </template>

      </el-table-column>
      <el-table-column
          prop="deptId"
          label="部门"
          :formatter="deptFormatter"
          width="100">
      </el-table-column>
      <el-table-column
          prop="status"
          label="状态"
          :formatter="statusFormatter"
          width="120">
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="创建时间"
          width="180">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              icon="el-icon-edit"
              round
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)">编辑
          </el-button>
          <el-button round
                     size="mini"
                     type="primary"
                     @click="handleRole(scope.row)">分配角色
          </el-button>
          <el-button
              icon="el-icon-delete"
              size="mini"
              type="danger"
              @click="handleDelete(scope.row.id)">删除
          </el-button>
        </template>

      </el-table-column>
    </el-table>
    <el-pagination
        background
        layout="prev, pager, next"
        :current-page="current"
        :page-size="size"
        @current-change="changePage"
        :total="total">
    </el-pagination>

    <!-- 修改、添加用户弹框 -->
    <el-dialog title="用户" :visible.sync="roleFormVisible">
      <el-form :model="editUserForm" ref="editUserForm" :rules="editRules">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="editUserForm.userName" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="editUserForm.phonenumber" placeholder="手机号"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-select v-model="editUserForm.deptId" placeholder="部门" clearable>
            <el-option :key="d.id" v-for="d in deptList" :label="d.deptName" :value="d.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" v-if="editUserForm.oper=='add'" prop="password">
          <el-input v-model="editUserForm.password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editUserForm.status" placeholder="状态" clearable>
            <el-option label="正常" value="0"></el-option>
            <el-option label="停用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
              class="avatar-uploader"
              action
              :show-file-list="false"
              :auto-upload="true"
              :http-request="uploadAvatar"
              :on-success="uploadSuccess"
              :before-upload="beforeAvatarUpload">
            <img style="width: 200px;height: 200px" v-if="editUserForm.avatar" :src="editUserForm.avatar"
                 class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser(editUserForm.oper)">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色弹框 -->
    <el-dialog title="用户角色" :visible.sync="roleMenuFormVisible" @close="resetRoleParam">
      <el-form>
        <el-form-item label="用户名">
          <el-tag type="success">{{currentRoleName}}</el-tag>
        </el-form-item>
        <el-form-item label="角色">
          <el-checkbox v-model="checkedRole" :checked="r.checked==1" :key="r.id" v-for="r in roleList" :label="r.id">{{ r.roleName }}
          </el-checkbox>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleMenuFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUserRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import User from "../api/user";
import {Message} from "element-ui";


export default {
  data() {
    return {
      total: 0,
      size: 3,
      current: 1,
      deptList: [],
      tableData: [],
      queryForm: {},
      createTimeArray: ['', ''],
      multipleSelection: [],
      roleFormVisible: false,
      roleMenuFormVisible: false,
      editUserForm: {
      },
      checkedRole: [],
      roleList: [],
      currentRoleName:'',
      currentRoleId:'',

      editRules: {
        userName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phonenumber: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '请选择部门', trigger: 'blur' }
        ],
      }
    }
  },
  created() {
    this.onQuery();
    this.getDeptList();
  },
  methods: {
    changePage(page) {
      console.log('page==', page)
      this.current = page
      this.onQuery();
    },
    async onQuery() {
      this.queryForm.current = this.current
      if (this.createTimeArray && this.createTimeArray.length == 2) {
        this.queryForm.startDate = this.createTimeArray[0]
        this.queryForm.endDate = this.createTimeArray[1]
      } else {
        this.queryForm.startDate = ''
        this.queryForm.endDate = ''
      }
      this.queryForm.size = this.size
      let response = await User.getUserPage(this.queryForm);
      this.tableData = response.records;
      this.total = response.total;
      this.size = response.size;
      this.current = response.current;
    },
    async getDeptList() {
      this.deptList = await User.getDeptList();

    },
    statusFormatter(row) {
      if (row.status == 0) {
        return "正常";
      } else if (row.status == 1) {
        return "停用";
      } else {
        return "-";
      }
    },
    deptFormatter(row) {
      let deptId = row.deptId;
      if (this.deptList && this.deptList.length>0){
        let deptName = this.deptList.filter(o => o.id == deptId).pop().deptName
        return deptName;
      }
      return ''

    },
    //批量删除
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection, 'this is selected')
    },
    //批量删除
    async batchDel() {
      if (this.multipleSelection) {
        var idList = []
        this.multipleSelection.forEach(o => {
          idList.push(o.id)
        })
      }
      if (idList.length == 0) {
        Message.error("请至少选择一条数据！")
        return;
      }
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {

        await User.deleteUser({"ids": idList});
        this.onQuery();
      }).catch(() =>{

      })
    },
    // 删除
    async handleDelete(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await User.deleteUser({"ids":id});
        this.onQuery();
      }).catch(() =>{

      })

    },
    // 点击编辑
    handleEdit(row) {
      this.roleFormVisible = true;
      this.roleFormVisible = true;
      // this.editUserForm = JSON.parse(JSON.stringify(this.row))  把复杂类型先转成字符串 字符串复制没有引用问题 然后再转过来
      this.editUserForm = {...row}; //es6解构赋值写法（把复杂类型的对象里的属性是简单类型的 一个个复制属性过去）如果对象里只有简单类型 没有复杂类型用解构赋值即可
      this.editUserForm.oper = 'update'
    },
    // 点击添加
    handleAdd() {
      this.roleFormVisible = true;
      this.roleFormVisible = true;
      // this.editUserForm = JSON.parse(JSON.stringify(this.row))  把复杂类型先转成字符串 字符串复制没有引用问题 然后再转过来
      this.editUserForm = {avatar:''}; //es6解构赋值写法（把复杂类型的对象里的属性是简单类型的 一个个复制属性过去）如果对象里只有简单类型 没有复杂类型用解构赋值即可
      this.editUserForm.oper = 'add'
    },
    resetRoleParam(){
      console.log('------resetRoleParam------')
      this.currentRoleId=''
      this.currentRoleName=''
      this.checkedRole= []
      this.roleList= []
    },
    // 点击分配角色
    async handleRole(row) {
      this.roleMenuFormVisible = true;
      this.currentRoleId=row.id
      this.currentRoleName=row.userName
      console.log(row.id,'-----+++++++')
      let response = await User.getRoleByUser({"userId":row.id});
      this.roleList = response.data;
    },
    async uploadAvatar(data) {
      const formdata = new FormData()
      formdata.append('file', data.file)
      let axiosResponse = await User.upload(formdata);
      console.log('图片地址', axiosResponse)
      // let url = await User.upload(formdata).data;
      // console.log('图片地址',url)
      this.editUserForm.avatar = axiosResponse.data;
      console.log( this.editUserForm.avatar)
    },
    uploadSuccess(){

    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
     saveUser(oper) {
      this.$refs.editUserForm.validate(  async (valid) => {
        if (valid) {
          if (oper == "update") {
            await User.updateUser(this.editUserForm);
          }
          if (oper == "add") {
            await User.addUser(this.editUserForm);
          }
          this.roleFormVisible = false
          this.editUserForm = {}
          this.onQuery();
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    async saveUserRole() {
      await User.saveUserRole({"id":this.currentRoleId,"list":this.checkedRole});
      this.roleMenuFormVisible = false
    }
  }
}
</script>

<style scoped>

</style>